package com.scrx.ymg.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.scrx.ymg.entity.Commission;
import com.scrx.ymg.entity.Distribution;
import com.scrx.ymg.entity.GoodsType;
import com.scrx.ymg.entity.HeadEntrepot;
import com.scrx.ymg.entity.IndexBanner;
import com.scrx.ymg.service.distribution.IDistributionService;
import com.scrx.ymg.service.head.IHeadService;
import com.scrx.ymg.service.user.IUserService;
import com.scrx.ymg.service.util.IUtilService;
import com.scrx.ymg.util.BaseUtil;
import com.scrx.ymg.util.CodeUtil;

import com.scrx.ymg.util.PayConfigUtil;
import com.scrx.ymg.util.SnCalUtil;
import com.scrx.ymg.util.WeChatDecode;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/utilAction")
public class UtilAction {
	
	@Autowired
    private	IUserService  users;
	
	@Autowired
    private	IHeadService  heads;
	
	@Autowired
    private	IUtilService utils;
	
	@Autowired
	private IDistributionService diss;
	
	/**
	 * 得到用户电话
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/getUserPhone",produces = "text/json;charset=UTF-8")
	public String getUserPhone(String encryptedData,String userID,String iv){
		 JSONObject temp=WeChatDecode.getUserInfo(encryptedData, userID, iv);
		Gson gson = new Gson();
		return gson.toJson(temp);
	}
	
	
	
	/**
	 * 得到用户佣金信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/getDistribution",produces = "text/json;charset=UTF-8")
	public String getDistribution(int userID){
		Distribution distribution =diss.getDistribution(userID);
		Gson gson = new Gson();
		return gson.toJson(distribution);
	}
	
	/**
	 * 更新佣金设置
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/updateCommission",produces = "text/json;charset=UTF-8")
	public String updateCommission(Commission comm){
		return utils.updateCommission(comm);
	}
	
	/**
	 * 查询佣金设置
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/getCommission",produces = "text/json;charset=UTF-8")
	public String getCommission(){
		Commission comm=utils.getCommission();
		Gson gson = new Gson();
		return gson.toJson(comm);
	}
	
	
	
	/**
	 * 根据经纬度得到当前区域地址
	 * @return  
	 * @百度密匙btsVVWf0TM1zUBEbzFz6QqWF
	 */
	@ResponseBody
	@RequestMapping(value ="/getmapinfo",produces = "text/json;charset=UTF-8")
	public String getmapinfo(String latitude,String longitude){
		String temp="";
		//String sn=SnCalUtil.getSN();
	try {
//		URI uri = new URI("http://api.map.baidu.com/geocoder/v2/?address=百度大厦&output=json&"
//				+ "ak=je6odQaA7sXq2MmrqxE1jQ8NZQ4pgySg"+"&sn="+ sn);
		URI uri = new URI("http://api.map.baidu.com/geocoder/v2/?ak=je6odQaA7sXq2MmrqxE1jQ8NZQ4pgySg"
				+ "&callback=renderReverse"
				+ "&location=" +latitude + ',' + longitude + "&output=json&pois=1");
		//System.out.println(uri);
		SimpleClientHttpRequestFactory schr = new SimpleClientHttpRequestFactory();
		ClientHttpRequest chr = schr.createRequest(uri, HttpMethod.POST);
		ClientHttpResponse res = chr.execute();  
		InputStream is = res.getBody(); //获得返回数据,注意这里是个流
		InputStreamReader isr = new InputStreamReader(is,"utf-8");
		BufferedReader br = new BufferedReader(isr);
		String str = "";
		while((str = br.readLine())!=null){
			temp=str;
		}
		//System.out.println(temp);
	} catch (URISyntaxException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return temp;
	}
	
	/**
	 * 使用code请求微信服务器拿到openid,
	 * @param code 用户登录code
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/wxLogin",produces = "text/json;charset=UTF-8")
	public String wxLogin(String code,String username,int referrerId,String headportrait){

		String temp="";
		try {
			URI uri = new URI("https://api.weixin.qq.com/sns/jscode2session?"
					+ "appid="+PayConfigUtil.APPID+"&secret="+PayConfigUtil.SECRET
					+"&js_code="+code+"&grant_type=authorization_code");
			SimpleClientHttpRequestFactory schr = new SimpleClientHttpRequestFactory();
			ClientHttpRequest chr = schr.createRequest(uri, HttpMethod.POST);
			ClientHttpResponse res = chr.execute();
			InputStream is = res.getBody(); //获得返回数据,注意这里是个流
			InputStreamReader isr = new InputStreamReader(is,"utf-8");
			BufferedReader br = new BufferedReader(isr);
			String str = "";
			//将输入流写到变量
			while((str = br.readLine())!=null){
				temp=str;
			}
			//将变量转化为json对象
			JsonObject returnData = new JsonParser().parse(temp).getAsJsonObject();
			//替换多余引号
			String session_key = (returnData.get("session_key").toString()).replaceAll("\"","");
			//String expires_in = (returnData.get("expires_in").toString()).replaceAll("\"","");
			String openid = (returnData.get("openid").toString()).replaceAll("\"","");
			//判断用户是否已经存在,不存在则新建.返回userID
			temp=users.saveifnull(username,openid,referrerId,headportrait);
			BaseUtil.sessionKey.put(temp, session_key);
			     
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return temp;
	}
	
	/**
	 * 添加商品分类
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/addGoodsType",produces = "text/json;charset=UTF-8")
	public String addGoodsType(GoodsType goodsType){
		return heads.addGoodsType(goodsType);
	}
	
	/**
	 * 修改商品分类
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/updateGoodsType",produces = "text/json;charset=UTF-8")
	public String updateGoodsType(GoodsType goodsType){
		return heads.updateGoodsType(goodsType);
	}
	
	/**
	 * 审核商品
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/auditProduct",produces = "text/json;charset=UTF-8")
	public String auditProduct(HeadEntrepot head){
		return heads.auditProduct(head);
	}
	
	/**
	 * 绑定商家ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/bindingMerchantID",produces = "text/json;charset=UTF-8")
	public String bindingMerchantID(int userID){
		return utils.bindingMerchantID(userID);
	}
	


	/**
	   * 新增首页banner
	   * @return
	   */
	  @ResponseBody
	  @RequestMapping(value = "/createIndexBanner", produces = "text/json;charset=UTF-8")
	  public String createIndexBanner(IndexBanner Indexbanner,MultipartFile bannerFile) {
	    return utils.createIndexBanner(Indexbanner,bannerFile);
	  }
	  /**
	   * 查询首页banner
	   * @return
	   */
	  @ResponseBody
	  @RequestMapping(value = "/selectIndexBanner", produces = "text/json;charset=UTF-8")
	  public String selectIndexBanner(IndexBanner Indexbanner) {
	    Gson gson = new Gson();
	    return gson.toJson(utils.selectIndexBanner(Indexbanner));
	  }
	  /**
	   * 修改首页banner
	   * @return
	   */
	  @ResponseBody
	  @RequestMapping(value = "/updateIndexBanner", produces = "text/json;charset=UTF-8")
	  public String updateIndexBanner(IndexBanner Indexbanner,MultipartFile bannerFile) {
	    return utils.updateIndexBanner(Indexbanner,bannerFile);
	  }
	  /**
	   * 删除首页banner
	   * @return
	   */
	  @ResponseBody
	  @RequestMapping(value = "/deleteIndexBanner", produces = "text/json;charset=UTF-8")
	  public String deleteIndexBanner(int id) {
	    return utils.deleteIndexBanner(id);
	  }

	
	
	

}
